<template>
  <div class="goods-container">
    <el-dialog
      :title="modallType === 0 ? '商品上架' : '商品编辑'"
      :visible.sync="dialogVisible"
      width="49%"
      :before-close="handleClose"
    >
      <!-- 用户的表单信息 -->
      <el-form
        ref="form"
        :rules="rules"
        :inline="true"
        :model="form"
        label-width="80px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input
            placeholder="请填写商品名称"
            v-model="form.name"
            :disabled="modallType === 1"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品单价" prop="money">
          <el-input
            placeholder="请输入商品单价"
            v-model="form.money"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="img">
          <el-upload
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :limit="1"
            list-type="picture-card"
            ref="upload"
          >
            <img
              :src="form.img"
              alt=""
              width="148px"
              height="148px"
              v-if="form.img && this.imgShow"
            />
            <i class="el-icon-plus" v-else></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisibleImg">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="售卖店铺" prop="shops">
          <el-select v-model="form.shops" placeholder="请选择">
            <el-option
              :label="item.name"
              :value="item.name"
              v-for="item in shopTableData"
              :key="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input
            placeholder="请输入商品库存"
            v-model="form.stock"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
    <div class="header">
      <el-button type="primary" @click="handleAdd" class="addBtn"
        >+ 商品上架</el-button
      >
      <div class="select">
        <el-button type="info" @click="clearList">重置</el-button>
        <el-button type="primary" @click="getList">查询</el-button>
        <el-input
          v-model="goodsName.name"
          placeholder="请输入商品名称"
        ></el-input>
      </div>
    </div>
    <div class="goods">
      <el-row :gutter="20">
        <el-col :span="6" v-for="item in tableData" :key="item.name">
          <div class="grid-content bg-purple">
            <img :src="item.img" alt="" />
            <p class="name">{{ item.name }}</p>
            <p class="moneySon">惊爆价</p>
            <p class="money">￥{{ item.money }}</p>
            <p class="shops">{{ item.shops }} </p>
            <p class="type">{{  item.stock==0?'敬请期待':'热售中'}}</p>
            <div class="stockFar">
              <p class="stock">
                {{item.stock==0?'已被抢光！':`仅剩${item.stock}件！`}}
              </p>
            </div>
            <div class="triangle"></div>
            <p class="new">NEW</p>
            <el-button size="mini" @click="handleEdit(item)">编辑</el-button>
            <el-button size="mini" type="success" @click="handleDelete(item)"
              >下架</el-button
            >
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

 <script>
 import { shopList } from "../api/mockServeData/shop"
import { getGoods, addGoods, editGoods, delGoods} from "../api";
export default {
  data() {
    var validateName = (rule, value, callback) => {
      if (this.form.name === "") {
        callback(new Error("请输入商品名称"));
      } else {
        for (let i = 0; i < this.tableData.length; i++) {
          if (this.modallType === 0 && this.tableData[i].name === value) {
            console.log(rule, value, "rulevalue");
            return callback(new Error("这个商品名称被使用咯"));
          }
        }
      }
      callback();
    };
    var validateMoney = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入商品单价"));
      } else {
        if (this.form.money <= 0) {
          callback(new Error("商品单价不能小于或等于0"));
        }
        callback();
      }
    };
    var validateStock = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入商品库存"));
      } else {
        if (this.form.stock < 0) {
          callback(new Error("商品库存不能小于0"));
        }
        callback();
      }
    };
    return {
      goodsName: {
        name: "",
      },
      tableData: [],
      form: {
        name: "",
        money: "",
        img: "",
        stock: "",
        shops: "",
      },
      rules: {
        name: [
          {
            trigger: "blur",
            validator: validateName,
          },
        ],
        money: [
          {
            trigger: "blur",
            validator: validateMoney,
          },
        ],
        stock: [
          {
            trigger: "blur",
            validator: validateStock,
          },
        ],
        shops: [{ required: true, message: "请选择售卖店铺", trigger: "blur" }],
        img: [{ required: true, message: "请选择商品图片", trigger: "blur" }],
      },
      dialogVisible: false,
      dialogImageUrl: "",
      dialogVisibleImg: false,
      modallType: 0, // 0 表示新增的弹窗，1 表示编辑
      imgShow: true, // 控制编辑时表单内图片
      shopTableData: [], // Shop表单的数据
    };
  },
  methods: {
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 后续对表单数据的处理
          if (this.modallType === 0) {
            addGoods(this.form).then(() => {
              // 重新获取列表的接口
              this.getList();
            });
          } else {
            editGoods(this.form).then(() => {
              // 重新获取列表的接口
              this.getList();
            });
          }
          // 关闭弹窗
          this.handleClose();
        }
      });
    },
    getList() {
      getGoods({
        params: { ...this.goodsName },
      }).then(({ data }) => {
        console.log(data, "data");
        this.tableData = data.list;
      });
    },
    clearList() {
      this.goodsName.name = "";
      this.getList();
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisibleImg = true;
    },
    handleSuccess(file, fileList) {
      this.form.img = fileList.url;
      this.imgShow = false;
    },
    handleError() {
      alert("只能上传jpg/png文件，且不超过500kb");
    },
    handleExceed() {
      alert("只能上传一张图片哦");
    },
    handleAdd() {
      this.dialogVisible = true;
      this.modallType = 0;
    },
    handleEdit(item) {
      this.dialogVisible = true;
      this.modallType = 1;
      // 需要对当前行数据进行深拷贝
      this.form = {
        name: item.name,
        img: item.img,
        money: item.money,
        shops: item.shops,
        stock: item.stock,
      };
    },
    handleDelete(item) {
      this.$confirm("您确定要下架该商品？", "是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delGoods({ name: item.name }).then(() => {
            this.$message({
              type: "success",
              message: "下架成功!",
            });
            // 获取的列表数据
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消下架",
          });
        });
    },
    // 弹窗关闭的时候
    handleClose() {
      this.form = {
        name: "",
        img: "",
        money: "",
        stock: "",
      };
      this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.$refs.upload.clearFiles();
      this.imgShow = true;
    },
    cancel() {
      this.handleClose();
    },
  },
  mounted() {
    this.getList();
    this.shopTableData=shopList;
  },
  computed: {

  }
}
</script>

<style scoped lang="less">
/deep/.header {
  display: flex;
  .addBtn {
    width: 120px;
    height: 40px;
  }
  .select {
    width: 100%;
    margin: 0 0 25px 0;
    .el-input {
      float: right;
      width: 15%;
      margin: 0 8px 0 0;
    }
    .el-button--primary {
      float: right;
      margin: 0 3px 0 0;
    }
    .el-button--info {
      float: right;
    }
  }
}
.goods {
  border: 1px solid #ebeef5;
  border-radius: 20px;
  box-shadow: 0 6px 6px hsl(0deg 0% 0% / 0.3);
  overflow-x: hidden;
  overflow-y: auto;
  height: 500px;
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
    /deep/.el-col {
      border-radius: 4px;
      position: relative;
      img {
        height: 280px;
        width: 50%;
      }
      .name {
        position: absolute;
        top: 16%;
        left: calc(50% + 5px);
        font-size: 23px;
        font-weight: 900;
      }
      .shops {
        position: absolute;
        top: 22%;
        left: calc(50% + 5px);
        font-size: 14px;
      }
      .money {
        position: absolute;
        top: 32%;
        left: calc(50% - 5px);
        font-size: 30px;
        color: #95061c;
        font-style: oblique;
        font-weight: 900;
      }
      .moneySon {
        position: absolute;
        top: 28%;
        left: calc(50% + 5px);
        font-size: 18px;
        color: #95061c;
      }
      .type {
        position: absolute;
        top: 41%;
        left: calc(50% + 5px);
        font-size: 16px;
      }
      .stockFar {
        position: absolute;
        top: 46%;
        left: calc(50% + 5px);
        width: 140px;
        height: 25px;
        border-radius: 5px;
        background-color: #95061c;
        text-align: center;
        .stock {
          font-size: 18px;
          color: #ffffff;
        }
      }
      .triangle {
        position: absolute;
        top: 0;
        left: 0;
        border-top: solid 40px #d40d20;
        border-bottom: solid 40px transparent;
        border-left: solid 75px #d40d20;
        border-right: solid 75px transparent;
      }
      .new {
        position: absolute;
        top: 15px;
        left: 25px;
        font-size: 18px;
        font-weight: 900;
        color: #ffffff;
      }
      .el-button--default {
        position: absolute;
        top: 60%;
        left: calc(50% + 28px);
      }
      .el-button--success {
        position: absolute;
        top: 60%;
        left: calc(50% + 78px);
      }
    }
  }

  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #ffffff;
    margin: 0 0 150px 0;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
}
</style>